﻿using ShSoft.Common.PoweredByLee;
using SlamDunk.CMS.BLL;
using SlamDunk.CMS.Model;
using SlamDunk.CMS.Model.FormatModel;
using SlamDunk.CMS.Model.ViewModel;
using SlamDunk.CMS.UI.Controllers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using SlamDunk.CMS.Model.DataModel;

namespace SlamDunk.CMS.UI.Areas.Admin.Controllers
{
    /// <summary>
    /// Link控制器
    /// </summary>
    public class LinkController : BaseController
    {

        #region 00.实例化业务层对象
        /// <summary>
        /// 实例化业务层对象
        /// </summary>
        private readonly LinkBll LinkBll = new LinkBll();
        private readonly LinkCategoryBll LinkCategoryBll = new LinkCategoryBll();
        private readonly List<LinkCategory> linkCategoryList;

        /// <summary>
        /// 构造方法
        /// </summary>
        public LinkController()
        {
            this.linkCategoryList = this.LinkCategoryBll.GetModelList();
        }
        #endregion

        #region 01.加载视图
        /// <summary>
        /// 加载列表视图
        /// </summary>
        /// <returns>列表视图</returns>
        public ActionResult Index()
        {
            this.ViewBag.CategoryList = this.linkCategoryList;
            return this.View();
        }
        #endregion

        #region 02.加载列表
        /// <summary>
        /// 加载列表
        /// </summary>
        /// <returns>EasyUI要求的json格式数据</returns>
        public ActionResult List()
        {
            //1.获取EasyUI请求的数据
            int pageIndex = string.IsNullOrEmpty(this.Request["page"]) ? 1 : int.Parse(this.Request["page"]);
            int pageSize = string.IsNullOrEmpty(this.Request["rows"]) ? 10 : int.Parse(this.Request["rows"]);
            int categoryId = string.IsNullOrEmpty(this.Request["category"]) ? 0 : int.Parse(this.Request["category"]);
            //2.根据请求查询数据并转换视图模型
            int pageCount, rowCount;
            List<LinkView> list = this.LinkBll.GetModelList(pageIndex, pageSize, out pageCount, out rowCount, categoryId).Select(x => x.ToViewModel()).ToList();
            //封装EasyUI模型
            DataGridModel dgModel = new DataGridModel()
            {
                total = rowCount,
                rows = list
            };
            //返回数据
            return this.Json(dgModel, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 03.添加——加载视图
        /// <summary>
        /// 添加——加载视图
        /// </summary>
        /// <returns>添加视图</returns>
        public ActionResult Add()
        {
            this.ViewBag.CategoryList = this.linkCategoryList;
            return this.View();
        }
        #endregion

        #region 04.添加——提交添加
        /// <summary>
        /// 添加——提交添加
        /// </summary>
        /// <param name="model">视图模型</param>
        /// <returns>JsonModel</returns>
        public ActionResult AddConfirm(LinkView model)
        {
            //校验模型
            if (this.ModelState.IsValid)
            {
                //1.转换数据模型
                Link dataModel = model.ToDataModel();
                //2.获取添加后的数据模型
                Link newModel = this.LinkBll.Add(dataModel);
                //3.非空校验
                if (newModel != null)
                {
                    //生成静态页
                    ThreadPool.QueueUserWorkItem(x =>
                    {
                        this.CreateHomeHtml();
                    });
                    return OperateContext.Current.JsonModel(1, "添加成功！");
                }
                else
                {
                    return OperateContext.Current.JsonModel(0, "添加失败！");
                }
            }
            else    //模型校验失败
            {
                return OperateContext.Current.JsonModel(0, "您提交的数据有误，请重试！");
            }

        }
        #endregion

        #region 05.删除单行
        /// <summary>
        /// 删除单行
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns>JsonModel</returns>
        public ActionResult DeleteSingle(int id)
        {
            //1.查询该实体是否存在
            Link model = this.LinkBll.GetModel(id);
            if (model == null)
            {
                return OperateContext.Current.JsonModel(0, "该实体不存在！");
            }
            else //2.如果存在，则删除
            {
                if (this.LinkBll.PhysicalDelete(id))
                {
                    //生成静态页
                    ThreadPool.QueueUserWorkItem(x =>
                    {
                        this.CreateHomeHtml();
                    });
                    return OperateContext.Current.JsonModel(1, "删除成功！");
                }
                else
                {
                    return OperateContext.Current.JsonModel(2, "删除失败，请重试！");
                }
            }
        }
        #endregion

        #region 06.删除选中行
        /// <summary>
        /// 删除选中的所有行
        /// </summary>
        /// <param name="selectedIds">选中行的Id</param>
        /// <returns>JsonModel</returns>
        public ActionResult DeleteSelected(string selectedIds)
        {
            try                 //涉及多次类型转换等操作，应处理异常
            {
                //1.处理前台选中的所有要删除的实体Id信息
                List<int> idList = selectedIds.Split(',').Select(x => int.Parse(x)).ToList();
                //2.执行批量删除操作
                idList.ForEach(x => this.LinkBll.PhysicalDelete(x));
                //生成静态页
                ThreadPool.QueueUserWorkItem(x =>
                {
                    this.CreateHomeHtml();
                });
                return OperateContext.Current.JsonModel(1, "删除成功！");
            }
            catch (Exception ex)
            {
                //写入日志

                //返回异常信息
                return OperateContext.Current.JsonModel(0, string.Format("删除失败，{0}", ex.Message));
            }
        }
        #endregion

        #region 07.修改—加载视图
        /// <summary>
        /// 加载要修改的行
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns>修改视图</returns>
        public ActionResult Edit(int id)
        {
            //1.根据给定主键查询数据模型并转化为视图模型
            LinkView viewModel = this.LinkBll.GetModel(id).ToViewModel();
            this.ViewBag.CategoryList = this.linkCategoryList;
            //2.返回视图 + 视图模型
            return this.View(viewModel);
        }
        #endregion

        #region 08.修改—提交修改
        /// <summary>
        /// 提交修改
        /// </summary>
        /// <param name="viewModel">视图模型</param>
        /// <returns>JsonModel</returns>
        public ActionResult EditConfirm(LinkView viewModel)
        {
            //校验模型
            if (this.ModelState.IsValid)
            {
                //1.将用户提交的视图模型转换为数据模型
                Link model = viewModel.ToDataModel();
                //2.执行修改操作
                if (this.LinkBll.Update(model))
                {
                    //生成静态页
                    ThreadPool.QueueUserWorkItem(x =>
                    {
                        this.CreateHomeHtml();
                    });
                    return OperateContext.Current.JsonModel(1, "修改成功！");
                }
                else
                {
                    return OperateContext.Current.JsonModel(0, "修改失败，请重试！");
                }
            }
            else    //模型校验失败
            {
                return OperateContext.Current.JsonModel(0, "您提交的数据有误，请重试！");
            }
        }
        #endregion

        #region 09.上传图片
        /// <summary>
        /// 上传图片方法
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult UploadImage()
        {
            //1.接收文件数据
            HttpPostedFileBase file = this.Request.Files["Filedata"];
            //2.获取文件名与文件扩展名
            string fileName = Path.GetFileName(file.FileName);
            string fileExt = Path.GetExtension(fileName);
            string streamMD5 = file.InputStream.ToMD5();    //获取文件流的MD5值
            //3.校验扩展名
            if (fileExt == ".jpg" || fileExt == ".png" || fileExt == ".gif" || fileExt == ".bmp")   //文件类型正确
            {
                #region //4.构造存储方案
                //1.构造文件夹路径
                string directory = string.Format("/UploadFiles/{0}/{1}/{2}/", DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
                //2.判断目标路径是否存在，创建文件夹
                Directory.CreateDirectory(Path.GetDirectoryName(this.Server.MapPath(directory)));
                //3.构造完整存储路径，路径 + 文件流的MD5值 + 文件扩展名
                string fullDirectory = string.Format("{0}{1}{2}", directory, streamMD5, fileExt);
                #endregion

                //5.保存文件
                file.SaveAs(this.Server.MapPath(fullDirectory));

                //6.返回客户端处理结果，图片路径
                return this.Content(string.Format("OK:{0}", fullDirectory));
            }
            else    //文件类型错误
            {
                //返回客户端处理结果
                return this.Content("Error:文件类型错误，请重试！");
            }
        }
        #endregion
    }
}
